package com.hc.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

/**
 * Servlet implementation class MobilePayInterface
 */
public class MobilePayInterface extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MobilePayInterface() {
        super();
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		OutputStream out = response.getOutputStream();
		out.write("pls use post method!".getBytes());
		out.flush();
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		InputStream in = request.getInputStream();
		OutputStream out = response.getOutputStream();

		String postData = readPostData(in);
		
		String respContent = handleRequests(postData);
		
		out.write(respContent.getBytes("UTF-8"));
		out.flush();
	}

	private String handleRequests(String postData) {
		JSONArray resps = new JSONArray();
		try {
			JSONArray requests = new JSONArray(postData);
			for(int i = 0; i < requests.length(); i++){
				String resp = dispatch(requests.getString(i));
				resps.put(resp);
			}
		} catch (JSONException e) {
			//请求格式错误
		}
		return resps.toString();
	}

	private String readPostData(InputStream in) throws IOException {
		ByteOutputStream data = new ByteOutputStream();
		byte[] bytes = new byte[1024];
		int size = 0;
		while ((size = in.read(bytes, 0, 1024)) > 0) {
			data.write(bytes, 0, size);
		}

		String postData = new String(data.getBytes(), 0, data.getCount(), "UTF-8");
		return postData;
	}

	private static final String ACTION_PACKAGE = "com.hc.server.actions.";

	@SuppressWarnings("unchecked")
	private String dispatch(String reqContent) {
		Response resp = new Response();

		try{
			Request req = null;
			try {
				req = Request.createRequest(reqContent);
			} catch (JSONException e) {
				resp.setErrResp(Error.API_FORMAT_ERR_CD, Error.API_FORMAT_ERR_MSG);
				return resp.toString();
			}
			String actionName = req.getRequestName();
			resp.setActionName(actionName);
			IAction action = null;
			try {
				Class<IAction> actionClass = (Class<IAction>) Class
						.forName(ACTION_PACKAGE + actionName);
				action = actionClass.newInstance();
			} catch (Exception e) {
				resp.setErrResp(Error.API_NOFOUND_ERR_CD, Error.API_NOFOUND_ERR_MSG
						+ actionName);
				return resp.toString();
			}
	
			action.execute(req, resp);
		}catch (Exception e) {
			e.printStackTrace();
			resp.setErrResp(Error.SERVER_SYS_ERR_CD, Error.SERVER_SYS_ERR_MSG);
		}
		return resp.toString();
	}
}
